class_name Enemy
extends Area2D

# 敌人与箭头的偏移距离，默认5像素
const ARROW_OFFSET := 5

@export var statsSrc: EnemyStatsSrc:
	set = setStats

@onready var sprite: Sprite2D = $Sprite2D
@onready var arrow: Sprite2D = $Arrow
@onready var stats: Stats = $Stats
@onready var intend: IntendUI = $Intend

var actionPick: ActionPick
var action: Action: set = setAction

func _ready():
	arrow.hide()

func setStats(value: EnemyStatsSrc) -> void:
	statsSrc = value.instance()
	if !statsSrc.statsChanged.is_connected(update):
		statsSrc.statsChanged.connect(update)
	init()

func init() -> void:
	if !statsSrc is StatsSrc: return push_error('状态信息不是敌人的')
	if !is_inside_tree(): await ready
		
	sprite.texture = statsSrc.skin
	arrow.position = Vector2.RIGHT * (sprite.get_rect().size.x / 2 + ARROW_OFFSET)
	initAi()
	renderStats()

# 更新ui及判断条件动作的执行
func update() -> void:
	renderStats()
	updateAction()

func renderStats() -> void:
	stats.render(statsSrc)

func getHurt(hurt: int) -> void:
	if statsSrc.health <= 0: return

	await Shaker.shake(self, 16, 0.2)
	statsSrc.getHurt(hurt)
	if statsSrc.health <= 0: queue_free()

# 检测卡牌目标选择器的进出
func _on_area_entered(_area: Area2D):
	arrow.show()

func _on_area_exited(_area: Area2D):
	arrow.hide()

#---ai关联逻辑---#
# 设置行动
func setAction(val: Action) -> void:
	action = val
	if action: intend.update(action.intend)

# 初始化ai设置
func initAi() -> void:
	if actionPick: actionPick.queue_free()

	var newPicker: ActionPick = statsSrc.ai.instantiate()
	add_child(newPicker)
	actionPick = newPicker
	actionPick.enemy = self

# 监听条件行动，是否需要执行
func updateAction() -> void:
	if !actionPick: return
	if !action:
		action = actionPick.getAction()
		return
	
	var conditionAction := actionPick.getConditionAction()
	if conditionAction and action != conditionAction: action = conditionAction

# 行动开始
func startAction() -> void:
	statsSrc.armor = 0
	if !action: return
	action.performAction()
